package com.woniuxy.woniuhis.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.woniuxy.woniuhis.entity.Deposit;
import com.woniuxy.woniuhis.entity.Examination;
import com.woniuxy.woniuhis.entity.Inpatient;
import com.woniuxy.woniuhis.entity.Outpatient;
import com.woniuxy.woniuhis.entity.PayIn;
import com.woniuxy.woniuhis.entity.RecipeMedi;
import com.woniuxy.woniuhis.entity.RegisInfo;
import com.woniuxy.woniuhis.entity.RegisType;
import com.woniuxy.woniuhis.entity.SurgeryExe;
import com.woniuxy.woniuhis.exception.PayInServiceException;
import com.woniuxy.woniuhis.mapper.DepositMapper;
import com.woniuxy.woniuhis.mapper.ExaminationMapper;
import com.woniuxy.woniuhis.mapper.InpatientMapper;
import com.woniuxy.woniuhis.mapper.OutpatientMapper;
import com.woniuxy.woniuhis.mapper.PayInMapper;
import com.woniuxy.woniuhis.mapper.RecipeMediMapper;
import com.woniuxy.woniuhis.mapper.RegisInfoMapper;
import com.woniuxy.woniuhis.mapper.RegisTypeMapper;
import com.woniuxy.woniuhis.mapper.SurgeryExeMapper;
import com.woniuxy.woniuhis.service.PayInService;
import com.woniuxy.woniuhis.util.PayInDetails;
import com.woniuxy.woniuhis.util.UUIDUtil;
@Service
public class PayInServiceImpl implements PayInService{
	@Autowired
	PayInMapper payInMapper;
	@Autowired
	InpatientMapper inpatientMapper;
	@Autowired
	ExaminationMapper examinationMapper;
	@Autowired
	RecipeMediMapper recipeMediMapper;
	@Autowired
	SurgeryExeMapper surgeryExeMapper;
	@Autowired
	DepositMapper depositMapper;
	@Autowired
	RegisInfoMapper regisInfoMapper;
	@Autowired
	RegisTypeMapper regisTypeMapper;
	@Autowired
	OutpatientMapper outpatientMapper;
	@Override
	public void addPayIn(PayIn payIn) {
		try {
			payInMapper.insertPayIn(payIn);
		} catch (Exception e) {
			e.printStackTrace();
			throw new PayInServiceException();
		}				
	}

	@Override
	public void delPayInById(String payInId) {
		try {
			//可能是删除一个订单，也可能删除一批订单，所以要遍历
			String[] payInIds = payInId.split(",");
			for(String id:payInIds) {
				payInMapper.deletePayInById(id);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new PayInServiceException();
		}				
	}

	@Override
	public void modifyPayIn(PayIn payIn) {
		try {
			payInMapper.updatePayIn(payIn);
		} catch (Exception e) {
			e.printStackTrace();
			throw new PayInServiceException();
		}			
	}

	@Override
	public PayIn findPayInById(String payInId) {
		try {
			PayIn payIn = payInMapper.selectPayInById(payInId);
			return payIn;
		} catch (Exception e) {
			e.printStackTrace();
			throw new PayInServiceException();
		}		
	}

	@Override
	public List<PayIn> findPayIn(PayIn payIn, Date beginDate, Date endDate) {
		try {
			List<PayIn> payIns = payInMapper.selectPayIn(payIn, beginDate, endDate);
			return payIns;
		} catch (Exception e) {
			e.printStackTrace();
			throw new PayInServiceException();
		}
	}

	@Override
	//查询患者列表
	public List<Inpatient> findInpatientPayIn(Inpatient condition, Date beginDate, Date endDate) {
		try {
			List<Inpatient> inp = inpatientMapper.selectInpatientByPay(condition, beginDate, endDate);
			Double total;
			Double debt;
			for(Inpatient i:inp) {
				total = new Double(0);
				debt = new Double(0);
				//查询检查表，通过状态判断已交和未交
				List<Examination> exs = examinationMapper.selectExaminationByInpaientId(i.getInpatientId());
				for(Examination ex:exs) {
					if(ex.getPayStatus()) {
						total+=ex.getExaminationTotal();
					}else {
						debt+=ex.getExaminationTotal();
					}
				}
				//查询药品表，通过状态判断已交和未交
				List<RecipeMedi> res = recipeMediMapper.selectRecipeMediByInpaientId(i.getInpatientId());
				for(RecipeMedi re:res) {
					if(re.getPayStatus()) {
						total+=re.getRecipeMediTotal();
					}else {
						debt+=re.getRecipeMediTotal();
					}
				}
				//查询手术表，通过状态判断已交和未交
				List<SurgeryExe> sus = surgeryExeMapper.selectSurgeryExeByInpaientId(i.getInpatientId());
				if(sus != null) {
					for(SurgeryExe su:sus) {
						if(su.getStatus()) {
							total+=su.getSurgeryExePrice();
						}else {
							debt+=su.getSurgeryExePrice();
						}
					}
				}
				//total是已交金额
				i.setInpatientFamlilyName(total.toString());
				//查询押金
				Deposit deposit = depositMapper.selectDepositByInpaientId(i.getInpatientId());
				//debt是未交金额，如果查到有押金就加上押金
				if(deposit!=null) {
					debt=debt-deposit.getBalance().doubleValue();
				}
				i.setInpatientFamlilyTel(debt.toString());
			}
			return inp;
		} catch (Exception e) {
			e.printStackTrace();
			throw new PayInServiceException();
		}
	}

	@Override
	/**
	 * 查询订单详情
	 */
	public List<PayInDetails> findPayInDetails(PayIn payIn) {
		try {
			List<PayInDetails> selectPayInExam = payInMapper.selectPayInExam(payIn);
			for(PayInDetails s:selectPayInExam) {
			s.setInItemid("检查");
			}
			List<PayInDetails> selectPayInReci = payInMapper.selectPayInReci(payIn);
			for(PayInDetails s:selectPayInReci) {
			s.setInItemid("药品");
			}
			List<PayInDetails> selectPayInSurg = payInMapper.selectPayInSurg(payIn);
			for(PayInDetails s:selectPayInSurg) {
			s.setInItemid("手术");
			}
			List<PayInDetails> details = new ArrayList<PayInDetails>();
			details.addAll(selectPayInExam);
			details.addAll(selectPayInReci);
			details.addAll(selectPayInSurg);
			return details;
		} catch (Exception e) {
			e.printStackTrace();
			throw new PayInServiceException();
		}
	}

	@Override
	/**
	 * @param typeid 项目编号
	 * @param inItemid 项目类型e-检查 r-药品 s-手术
	 * @param payInStatus 支付状态
	 * 删除一个项目订单，如果已经付款，还要删除付款订单
	 */
	public void delPayInAndDetails(String typeid, String inItemid, String payInStatus) {
		try {
			//如果已支付，需要删除订单
			if("1".equals(payInStatus)) {
				payInMapper.deletePayInByReceiptId(typeid);
			}
			switch (inItemid) {
			case "检查":
				examinationMapper.deleteExaminationById(typeid);
				break;
			case "药品":
				recipeMediMapper.deleteRecipeMediById(typeid);
				break;
			case "手术":
				surgeryExeMapper.deleteSurgeryExeById(typeid);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new PayInServiceException();
		}
	}

	@Override
	/**
	 * 修改一个项目订单，如果已经付款，还要修改付款订单
	 */
	public void modifyPayInAndDetails(PayInDetails payInDetails) {
		System.out.println(payInDetails);
		try {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			boolean status=(payInDetails.getPatientId().equals("1")?true:false);
			PayIn payIn=new PayIn();
			//未支付改为已支付就添加一个订单
			if("0".equals(payInDetails.getPayInStatus())&&"1".equals(payInDetails.getPatientId())) {
				payIn.setPayInId(UUIDUtil.uuid32());
				payIn.setPayInMoney(new BigDecimal(payInDetails.getPayInPrice()));
				payIn.setReceiptId(payInDetails.getTypeid());
				payIn.setReceiptDate(sdf.parse(payInDetails.getPayInDate()));
				payIn.setPayWayId("2");
				payIn.setDepId("3");
				payInMapper.insertPayIn(payIn);
			//原来是已支付就需要删除或更新订单
			}else if ("1".equals(payInDetails.getPayInStatus())) {
				if("0".equals(payInDetails.getPatientId())) {
					payInMapper.deletePayInByReceiptId(payInDetails.getTypeid());
				}else if ("1".equals(payInDetails.getPatientId())) {
					payIn.setReceiptId(payInDetails.getTypeid());
					payIn.setPayInMoney(new BigDecimal(payInDetails.getPayInPrice()));
					payIn.setReceiptDate(sdf.parse(payInDetails.getPayInDate()));
					payInMapper.updatePayInByReceiptId(payIn);
				}
			}
			//判断修改项目订单
			switch (payInDetails.getInItemid()) {
			case "检查":
				Examination ex=new Examination();
				ex.setExaminationId(payInDetails.getTypeid());
				ex.setExaminationTotal(Double.parseDouble(payInDetails.getPayInPrice()));
				ex.setExaminationDate(sdf.parse(payInDetails.getPayInDate()));
				ex.setPayStatus(status);
				examinationMapper.updateExamination(ex);
				break;
			case "药品":
				RecipeMedi recipeMedi=new RecipeMedi();
				recipeMedi.setRecipeMediId(payInDetails.getTypeid());
				recipeMedi.setRecipeMediTotal(Double.parseDouble(payInDetails.getPayInPrice()));
				recipeMedi.setRecipeMediDate(sdf.parse(payInDetails.getPayInDate()));
				recipeMedi.setPayStatus(status);
				recipeMediMapper.updateRecipeMedi(recipeMedi);
				break;
			case "手术":
				SurgeryExe surgeryExe=new SurgeryExe();
				surgeryExe.setSurgeryExeId(payInDetails.getTypeid());
				surgeryExe.setSurgeryExePrice(Double.parseDouble(payInDetails.getPayInPrice()));
				surgeryExe.setStartTime(sdf.parse(payInDetails.getPayInDate()));
				surgeryExe.setStatus(status);
				surgeryExeMapper.updateSurgeryExe(surgeryExe);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new PayInServiceException();
		}
	}

	@Override
	/**
	 * 查询押金账单
	 */
	public List<PayIn> findPayInDeposit(PayIn payIn, Date beginDate, Date endDate) {
		try {
			List<PayIn> payIns = payInMapper.selectPayInDeposit(payIn, beginDate, endDate);
			return payIns;
		} catch (Exception e) {
			e.printStackTrace();
			throw new PayInServiceException();
		}

	}

	@Override
	/**
	 * 查询门诊账单
	 */
	public List<PayInDetails> findPayInOut(PayIn payIn) {
		try {
			List<PayInDetails> payInDetails = payInMapper.selectPayInOut(payIn);
			for(PayInDetails p:payInDetails) {
				RegisType type = regisTypeMapper.selectRegisTypeById(p.getPayInPrice());
				p.setPayInPrice(type.getRegisTypePrice().toString());
			}
			return payInDetails;
		} catch (Exception e) {
			e.printStackTrace();
			throw new PayInServiceException();
		}
	}
	
	
	@Override
	/**
	 * 修改一个门诊订单，如果已经付款，还要修改付款订单
	 */
	public void modifyPayInAndOut(PayInDetails payInDetails) {
		System.out.println(payInDetails);
		try {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			boolean status=(payInDetails.getPatientId().equals("1")?true:false);
			PayIn payIn=new PayIn();
			//未支付改为已支付就添加一个订单
			if("0".equals(payInDetails.getPayInStatus())&&"1".equals(payInDetails.getPatientId())) {
				payIn.setPayInId(UUIDUtil.uuid32());
				payIn.setPayInMoney(new BigDecimal(payInDetails.getPayInPrice()));
				payIn.setReceiptId(payInDetails.getTypeid());
				payIn.setReceiptDate(sdf.parse(payInDetails.getPayInDate()));
				payIn.setPayWayId("2");
				payIn.setDepId("3");
				payInMapper.insertPayIn(payIn);
				//根据挂号id查询出挂号信息
				RegisInfo regisInfo = regisInfoMapper.selectRegisInfoById(payInDetails.getTypeid());
				//初始化一条门诊信息
				Outpatient outpatient = new Outpatient();
				//设置主键
				outpatient.setOutpatientId(UUIDUtil.uuid32());
				//设置患者id
				outpatient.setPatientId(regisInfo.getPatientId());
				//设置科室id
				outpatient.setOfficeId(regisInfo.getOfficeId());
				//初始化开始结束状态
				outpatient.setStart_status(false);
				outpatient.setEnd_status(false);
				//插入一条门诊信息
				outpatientMapper.insertOutpatient(outpatient);
			//原来是已支付就需要删除或更新订单
			}else if ("1".equals(payInDetails.getPayInStatus())) {
				if("0".equals(payInDetails.getPatientId())) {
					payInMapper.deletePayInByReceiptId(payInDetails.getTypeid());
				}else if ("1".equals(payInDetails.getPatientId())) {
					payIn.setReceiptId(payInDetails.getTypeid());
					payIn.setPayInMoney(new BigDecimal(payInDetails.getPayInPrice()));
					payIn.setReceiptDate(sdf.parse(payInDetails.getPayInDate()));
					payInMapper.updatePayInByReceiptId(payIn);
				}
			}
			RegisInfo regisInfo=new RegisInfo();
			regisInfo.setRegisInfoId(payInDetails.getTypeid());
			regisInfo.setRegisDate(sdf.parse(payInDetails.getPayInDate()));
			regisInfo.setPayStatus(status);
			regisInfoMapper.updateRegisInfo(regisInfo);
		} catch (Exception e) {
			e.printStackTrace();
			throw new PayInServiceException();
		}
	}
}
